package com.yunduo.controller.word;

import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServerCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.RetunData.statuscode.impl.WorldCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Log;
import com.yunduo.entity.vo.HistoryLoginData;
import com.yunduo.service.LogService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 管理员系统
 */
@RequiresRoles("admin")
@RestController
@RequestMapping("/world/system")
public class SystemController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private LogService logService;

    //登录人数统计
    @GetMapping("/onlineUserCount")
    public CommonReturn getOnlineUserCount(){
        SetOperations setOperations = redisTemplate.opsForSet();
        Long onlineSize = setOperations.size(ServerCode.ONLINE_ACCOUNT_TOTAL.getInfo());
        Long totalSize = setOperations.size(ServerCode.TODAY_LOGIN_ACCOUNT_TOAL.getInfo());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS)
                    .setData("onlineSize",onlineSize)
                    .setData("totalSize", totalSize);
    }

    //历史登录人数（7天）
    @GetMapping("/historyLoginData")
    public CommonReturn getHistoryLoginDate(){
        //从日志表中查询出需要的7条数据
        List<Log> rolesByIds = logService.getRolesByIds(ServerCode.LOGIN_TOTAL_LOG.getInfo(), 7);
        Iterator<Log> iterator = rolesByIds.iterator();
        List<HistoryLoginData> data = new ArrayList<>();
        while (iterator.hasNext()){
            Log log = iterator.next();
            LocalDate date = LocalDate.from(log.getGmtCreate());
            Integer count = Integer.valueOf(log.getResult());
            data.add(new HistoryLoginData(date,count));
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("loginData",data);
    }

    //系统内存参数
    @GetMapping("/systemParams")
    public CommonReturn getSystemParams(){
        HashMap<String, Integer> systemInfo = YunDuoUtils.getSystemInfo();
        return CommonReturn.SUCCESS(ResultCode.SUCCESS)
                    .setData("useMemory",systemInfo.get("useMemory"))
                    .setData("maxMemory",systemInfo.get("maxMemory"));
    }
}
